package com.android.questions.ui.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;

import com.android.base.util.ActivityClickUtil;
import com.android.base.util.DQLog;
import com.android.base.util.DisplayUtil;
import com.android.base.util.ToastUtil;
import com.android.questions.R;
import com.android.questions.config.AppConfig;
import com.android.questions.config.LoginConfig;
import com.android.questions.databinding.DialogRedBubbleBinding;
import com.android.questions.util.AnimUtil;
import com.android.questions.util.sound.MediaBackManager;
import com.dq.ad.AdManager;
import com.dq.ad.UMManager;
import com.hx.currency.HXCurrencySDK;
import com.hx.currency.data.qa.api.QAWatchVideoResp;
import com.qq.e.o.ads.v2.error.AdError;
import com.qq.e.o.data.HttpUtil;
import com.qq.e.o.utils.JsonUtil;

import java.util.Random;

public class DialogRedBubble extends Dialog implements View.OnClickListener {
    public static int TYPE_BUBBLE = 0;// 气泡红包
    public static int TYPE_SURPRISE = 1;// 惊喜红包

    private DialogRedBubbleBinding bubbleBinding;
    private OnClickLister clickLister;
    private final Activity activity;
    private boolean isReward = true;
    private int dialogType = TYPE_BUBBLE;

    public DialogRedBubble(Activity a) {
        super(a, R.style.dialog_loading);
        this.activity = a;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bubbleBinding = DialogRedBubbleBinding.inflate(activity.getLayoutInflater());
        setContentView(bubbleBinding.getRoot());

        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = DisplayUtil.getScreenWidth(activity);
        lp.height = DisplayUtil.getScreenHeight(activity);
        getWindow().setAttributes(lp);

        getWindow().setWindowAnimations(R.style.dialog_answer_correct);

        setCancelable(false);
        setCanceledOnTouchOutside(false);
        initView();
        initLister();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        ActivityClickUtil.getInstance().clear();
        String title = "气泡红包";
        String tips = "观看激励视频越多\n气泡红包越大";
        if (dialogType == TYPE_SURPRISE) {
            title = "惊喜红包";
            tips = "每日限量赠送";
        }
        bubbleBinding.tvTitle.setText(title);
        bubbleBinding.tvTips.setText(tips);

        AnimUtil.receiveAnimM(activity, bubbleBinding.ivGet);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                bubbleBinding.ivClose.setVisibility(View.VISIBLE);
            }
        }, 3000);

        AdManager.getInstance().showNativeAD(activity, bubbleBinding.nativeContainer, DisplayUtil.getScreenWidthDp(activity) - 48, 0, AdManager.NATIVE_AD_TYPE_UP_IMAGE, false, new AdManager.OnNativeVideoADListener() {
            @Override
            public void onSuccess() {
                bubbleBinding.nativeContainer.setBackgroundColor(activity.getResources().getColor(R.color.Color_FFFFFF));
            }

            @Override
            public void onClosed() {
                bubbleBinding.nativeContainer.setBackgroundColor(activity.getResources().getColor(android.R.color.transparent));
            }

            @Override
            public void onError() {

            }

            @Override
            public void onClick() {

            }

            @Override
            public void onShow(View view) {

            }
        });

        AnimUtil.rotateAnim(bubbleBinding.ivCenterBg);
    }

    private void initLister() {
        bubbleBinding.ivCenter.setOnClickListener(this);
        bubbleBinding.ivClose.setOnClickListener(this);
    }

    public DialogRedBubble setType(int type) {
        this.dialogType = type;
        return this;
    }

    public DialogRedBubble setClickLister(OnClickLister lister) {
        this.clickLister = lister;
        return this;
    }

    @Override
    public void onClick(View v) {
        if (ActivityClickUtil.getInstance().isFastClick()) {
            //防止用户快速点击
            return;
        }
        dismiss();
        if (v.getId() == R.id.iv_center) {
            watchVideo();
        }
    }

    private void watchVideo() {
        isReward = false;
        if (AppConfig.hasNoAd()) {
            AppConfig.showNoAdToast(activity);
        } else {
            if (AppConfig.getBackMusic()) {
                MediaBackManager.getInstance(activity).pause();
            }
            AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
                @Override
                public void onClosed(String orderId) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    if (isReward) {
                        if (dialogType == TYPE_SURPRISE) {
                            UMManager.onEvent(UMManager.Event.Receive_SurpriseHongbao);
                        } else {
                            UMManager.onEvent(UMManager.Event.Receive_BubbleHongbao);
                        }
                        addCoin(orderId);
                    } else {
                        ToastUtil.showShortToast(activity, "未完整观看视频，领取失败");
                    }
                }

                @Override
                public void onReward() {
                    isReward = true;
                }

                @Override
                public void onShow(double ecpm) {
                }

                @Override
                public void onFailed(int i, AdError adError) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                }

                @Override
                public void onTimeout() {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                }
            });
        }
    }

    private void addCoin(String orderId) {
        int coin = new Random().nextInt(40) + 200;
        HXCurrencySDK.getInstance().qaWatchVideo(2, coin, orderId, new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String response) {
                DQLog.e("看视频补充金币成功：" + response);
                if (activity.isFinishing()) {
                    return;
                }
                QAWatchVideoResp qaWatchVideoResp = JsonUtil.parseObject(response, QAWatchVideoResp.class);
                if (qaWatchVideoResp != null) {
                    if (qaWatchVideoResp.getErrorCode() == 0) {
                        if (activity.isFinishing()) {
                            return;
                        }
                        double ra = qaWatchVideoResp.getRa();
                        LoginConfig.setUserCash(LoginConfig.getUserCash() + ra);

                        new DialogAddCoinResult(activity).setMoney(ra).setClickLister(new DialogAddCoinResult.OnClickLister() {
                            @Override
                            public void onReceive() {
                                if (clickLister != null) {
                                    clickLister.onReceive();
                                }
                            }
                        }).show();
                    } else {
                        String errorMessage = qaWatchVideoResp.getErrorMessage();
                        if (errorMessage.isEmpty()) {
                            errorMessage = "网络数据异常，领取失败";
                        }
                        ToastUtil.showShortToast(activity, errorMessage);
                    }
                } else {
                    ToastUtil.showShortToast(activity, "网络数据异常，领取失败");
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                ToastUtil.showShortToast(activity, "网络异常，领取失败");
            }
        });
    }

    public interface OnClickLister {
        void onReceive();
    }
}